// pages/allshop/allshop.js
Page({
   // 跳转到地图页面
   goToAllShop() {
    wx.navigateTo({
        url: '/pages/index/index'
    })
},

// 跳转到商铺详情页面
goToDetail(e){
  const index = e.currentTarget.dataset.index;
  const shopList = this.data.shopList;
  
  if (!shopList || !shopList[index]) {
    wx.showToast({
      title: '商品信息不存在',
      icon: 'none'
    });
    return;
  }

  const item = shopList[index];
  wx.navigateTo({
    url: `/pages/shopDetails/shopDetails?id=${item._id}`,
  })
},

//跳转到聊天页面
gochat(){
  wx.navigateTo({
    url: '',
  })
},
  /**
   * 页面的初始数据
   */
  data: {
    isRefreshing: false,
    isLoading: false,
    isCollected: false,
    shopInfo: {},
    shopList: [],
    pageSize: 10,
    currentPage: 1,
    hasMore: true,
    activeTab: 0,
    text:'如果同学不知道位置，可以点击下方地图按钮来查看地图哟'
  },

  // 辅助函数：处理列表数据
  _processShopData(data) {
    return data.map(item => {
      // 处理图片数组，限制最多显示两张图片
      if (item.image && typeof item.image === 'string') {
        item.image = [item.image].slice(0, 2);
      } else if (Array.isArray(item.image)) {
        item.image = item.image.slice(0, 2);
      } else {
        item.image = [];
      }

      if (item.createTime) {
        const createTime = new Date(item.createTime);
        const now = new Date();
        const diff = now - createTime;
        
        // 转换时间显示
        if (diff < 60000) { // 小于1分钟
          item.timeText = '刚刚';
        } else if (diff < 3600000) { // 小于1小时
          item.timeText = Math.floor(diff / 60000) + '分钟前';
        } else if (diff < 86400000) { // 小于24小时
          item.timeText = Math.floor(diff / 3600000) + '小时前';
        } else if (diff < 2592000000) { // 小于30天
          item.timeText = Math.floor(diff / 86400000) + '天前';
        } else { // 超过30天显示具体日期
          item.timeText = `${createTime.getFullYear()}-${createTime.getMonth() + 1}-${createTime.getDate()}`;
        }
      } else {
        item.timeText = '刚刚';
      }
      return item;
    });
  },

  // 处理关注按钮点击
  handleFollow(e) {
    const index = e.currentTarget.dataset.index;
    const shopList = this.data.shopList;
    shopList[index].isFollowed = !shopList[index].isFollowed;
    
    this.setData({
      shopList: shopList
    });
  },

  // 页面加载时获取数据
  // 处理图片加载错误
  handleImageError(e) {
    const index = e.currentTarget.dataset.index;
    const shopList = this.data.shopList;
    // 从图片数组中移除加载失败的图片
    shopList.forEach(item => {
      if (Array.isArray(item.image)) {
        item.image = item.image.filter((_, i) => i !== index);
      }
    });
    this.setData({ shopList });
  },

  // 处理头像加载错误
  handleAvatarError(e) {
    const index = e.currentTarget.dataset.index;
    const shopList = this.data.shopList;
    // 设置默认头像
    shopList[index].avatarUrl = '../../img/微信图片_20240320133042.jpg';
    this.setData({ shopList });
  },

  //点赞
  onLoad: async function() {
    try {
      const db = wx.cloud.database();
      let openid = null;
      let likedPosts = new Set();
      try {
        // 从本地存储获取点赞记录
        const localLikedPosts = wx.getStorageSync('likedPosts') || [];
        likedPosts = new Set(localLikedPosts);
        
        // 通过云函数获取用户openid
        const res = await wx.cloud.callFunction({
          name: 'getOpenId'
        });
        openid = res.result.openid;
        // 获取用户的点赞记录
        if (openid) {
          const likesRes = await db.collection('likes')
            .where({
              userId: openid
            })
            .get();
          // 合并云端和本地的点赞记录
          const cloudLikedPosts = new Set(likesRes.data.map(like => like.postId));
          likedPosts = new Set([...likedPosts, ...cloudLikedPosts]);
          // 更新本地存储
          wx.setStorageSync('likedPosts', Array.from(likedPosts));
        }
      } catch (openidErr) {
        console.error('获取用户openid失败：', openidErr);
      }
      // 获取帖子列表
      const postsRes = await db.collection('loudong')
        .orderBy('createTime', 'desc')
        .get();
      // 处理帖子数据，添加点赞状态
      const processedData = this._processShopData(postsRes.data).map(post => ({
        ...post,
        isLiked: likedPosts.has(post._id),
        likeCount: post.likeCount || 0
      }));
      this.setData({
        shopList: processedData
      });
    } catch (err) {
      console.error('加载数据失败：', err);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 加载更多数据
  loadMoreData() {
    if (!this.data.hasMore || this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    const db = wx.cloud.database();
    const currentPage = this.data.currentPage;
    const pageSize = this.data.pageSize;
    
    db.collection('loudong')
      .orderBy('createTime', 'desc')
      .skip((currentPage - 1) * pageSize)
      .limit(pageSize)
      .get()
      .then(res => {
        if (res.data && res.data.length > 0) {
          const processedData = this._processShopData(res.data);
          const existingIds = new Set(this.data.shopList.map(item => item._id));
          const uniqueNewData = processedData.filter(item => !existingIds.has(item._id));
          
          if (uniqueNewData.length > 0) {
            this.setData({
              shopList: [...this.data.shopList, ...uniqueNewData],
              currentPage: currentPage + 1,
              hasMore: res.data.length >= pageSize
            });
          } else {
            this.setData({ hasMore: false });
          }
        } else {
          this.setData({ hasMore: false });
        }
      })
      .catch(err => {
        console.error('获取数据失败：', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ isLoading: false });
      });
  },

//  点赞
// 下拉刷新
  onRefresherRefresh: function () {
    if (this.data.isRefreshing) return;
    
    this.setData({
      isRefreshing: true,
      currentPage: 1,
      hasMore: true
    });
    
    const db = wx.cloud.database();
    db.collection('loudong')
      .orderBy('createTime', 'desc')
      .limit(this.data.pageSize)
      .get()
      .then(res => {
        if (res.data) {
          const processedData = this._processShopData(res.data);
          this.setData({
            shopList: processedData,
            hasMore: res.data.length >= this.data.pageSize
          });
        }
      })
      .catch(err => {
        console.error('刷新数据失败：', err);
        wx.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ isRefreshing: false });
      });
  },

  onLikeTap: async function (e) {
  const index = e.currentTarget.dataset.index;
  const shopList = this.data.shopList;
  const item = shopList[index];
  if (!item) return;
  // 本地立即更新UI
  const originalIsLiked = item.isLiked;
  const originalLikeCount = item.likeCount || 0;
  if (item.isLiked) {
    item.isLiked = false;
    item.likeCount = Math.max(originalLikeCount - 1, 0);
  } else {
    item.isLiked = true;
    item.likeCount = originalLikeCount + 1;
  }
  this.setData({ shopList });
  
  // 更新本地存储的点赞状态
  let likedPosts = new Set(wx.getStorageSync('likedPosts') || []);
  if (item.isLiked) {
    likedPosts.add(item._id);
  } else {
    likedPosts.delete(item._id);
  }
  wx.setStorageSync('likedPosts', Array.from(likedPosts));
  // 异步处理数据库
  const db = wx.cloud.database();
  try {
    const res = await wx.cloud.callFunction({
      name: 'getOpenId'
    });
    const openid = res.result.openid;
    const likeCollection = db.collection('likes');
    const likeRecord = await likeCollection.where({
      postId: item._id,
      userId: openid
    }).get();
    const isLiked = likeRecord.data.length > 0;
    if (originalIsLiked) {
      // 取消点赞
      if (isLiked) {
        await likeCollection.where({
          postId: item._id,
          userId: openid
        }).remove();
        await db.collection('loudong').doc(item._id).update({
          data: {
            likeCount: db.command.inc(-1)
          }
        });
      }
    } else {
      // 添加点赞
      if (!isLiked) {
        await likeCollection.add({
          data: {
            postId: item._id,
            userId: openid,
            createTime: db.serverDate()
          }
        });
        await db.collection('loudong').doc(item._id).update({
          data: {
            likeCount: db.command.inc(1)
          }
        });
      }
    }
  } catch (err) {
    // 如果失败，回滚本地UI
    item.isLiked = originalIsLiked;
    item.likeCount = originalLikeCount;
    this.setData({ shopList });
    console.error('点赞操作失败：', err);
    wx.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
},

// 预览图片，放大和缩小
previewImage: function(e) {
  const url = e.currentTarget.dataset.url;
  const urls = e.currentTarget.dataset.urls;
  wx.previewImage({
    current: url,
    urls: urls
  });
}
})
